#include "myfuncs.h"
#include <QApplication>
#include <QMessageBox>

#ifndef CS
#include <QDebug>
#define CS qDebug()
#endif

using namespace cv;
using namespace std;

#define EXIT(msg, code)        \
    {                          \
        CS << qPrintable(msg); \
        return code;           \
    }

Mat imgDepth;
String winName;
int dmIntPos = 8;
bool showFalseColor = false;

void showImage()
{
    Mat imgDepth8bit, imgDepthShow;
    interceptDepthMap(imgDepth, imgDepth8bit, dmIntPos);
    if (showFalseColor)
        colorDisparity(imgDepth8bit, imgDepthShow);
    else
        imgDepthShow = imgDepth8bit;
    imshow(winName, imgDepthShow);
}

void onMouse(int event, int x, int y, int flag, void*)
{
    int depth = imgDepth.at<unsigned short>(y, x);
    QString msg = QString("Pos( %1, %2 ) Depth( %3 )").arg(x).arg(y).arg(depth);
    displayStatusBar(winName, msg.toStdString());

    if (event == EVENT_MBUTTONDOWN) {
        showFalseColor = !showFalseColor;
        showImage();
    }
}

void onTrackbar(int, void*)
{
    showImage();
}

int main(int argc, char* argv[])
{
    QApplication a(argc, argv);

    if (argc < 2)
        EXIT("Error: argc < 2", -1);
    QString fileName = QString::fromLocal8Bit(argv[1]);
    fileName = fileName.replace("\\", "/");
    CS << "filename:" << qPrintable(fileName);
    winName = fileName.mid(fileName.lastIndexOf("/") + 1).toStdString();

    // load depthmap
    imgDepth = imread(fileName.toLocal8Bit().toStdString(), IMREAD_UNCHANGED);
    if (imgDepth.empty())
        EXIT("load image failed!", -2);
    if (imgDepth.type() != CV_16UC1) {
        QMessageBox::critical(nullptr, "error", "The source image is not depthmap(16-bit unsigned)!");
        EXIT("error image format", -3);
    }
    showImage();

    setMouseCallback(winName, onMouse);
    createTrackbar("intercept", winName, &dmIntPos, 16, onTrackbar);

    return a.exec();
}
